package com.squid.templateProject.config.exception;


import com.squid.templateProject.bean.Return;
import com.squid.templateProject.bean.enums.SystemCodeMsgEnums;
import com.squid.templateProject.utils.IpUtils;
import com.squid.templateProject.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @author jh
 * @date 2022/12/6 16:07
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionConfig {
    /**
     * 指定异常处理方法
     **/
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public Return<Object> error(NullPointerException e, HttpServletRequest request) {
        ipSession(request, e);
        return Return.addResult(SystemCodeMsgEnums.NULL_POINT);
    }

    /**
     * 处理 form data方式调用接口对象参数校验失败抛出的异常
     *
     * @param e       e
     * @param request 请求
     * @return {@link Return }<{@link Object }>
     * @author jh
     * @date 2023/05/12
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Return<Object> bindExceptionHandler(BindException e, HttpServletRequest request) {
        ipSession(request, e);
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("; "));
        return Return.addResult(SystemCodeMsgEnums.PARAM_ERROR).message(message);
    }

    /**
     * 处理Get请求中 验证路径中 单个参数请求失败抛出异常
     *
     * @param e       e
     * @param request 请求
     * @return {@link Return }<{@link Object }>
     * @author jh
     * @date 2023/05/12
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Return<Object> constraintViolationExceptionHandler(ConstraintViolationException e, HttpServletRequest request) {
        ipSession(request, e);
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("; "));
        return Return.addResult(SystemCodeMsgEnums.PARAM_ERROR).message(message);
    }

    /**
     * 处理 json 请求体调用接口对象参数校验失败抛出的异常
     *
     * @param e       e
     * @param request 请求
     * @return {@link Return }<{@link Object }>
     * @author jh
     * @date 2023/05/12
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Return<Object> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e, HttpServletRequest request) {
        ipSession(request, e);
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("; "));
        return Return.addResult(SystemCodeMsgEnums.PARAM_ERROR).message(message);
    }

    /**
     * 通用异常处理方法
     **/
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Return<Object> error(Exception e, HttpServletRequest request) {
        ipSession(request, e);
        return Return.addResult(SystemCodeMsgEnums.ERROR)
                .request(request.getRequestURI());
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Return<Object> convertException(BusinessException e, HttpServletRequest request) {
        ipSession(request, e);
        return Return.failure().code(e.getCode()).request(request.getRequestURI()).message(e.getMessage());
    }

    @ExceptionHandler(ServerException.class)
    @ResponseBody
    public Return<Object> convertException(ServerException e, HttpServletRequest request) {
        ipSession(request, e);
        return Return.failure().code(e.getCode()).request(request.getRequestURI()).message(e.getMessage());
    }

    void ipSession(HttpServletRequest request, Exception e) {
        String currentTime = TimeUtils.getCurrentTime();
        String ip = IpUtils.ip(request);
        String sessionId = request.getRequestedSessionId();
        log.error("ip:{}  SessionId:{}  Stamp:{}", ip, sessionId, currentTime, e);
    }


}
